
clear;clc;
load("data.mat");
load("cnPulation.mat")

plot(X,Y,"bo");
xlabel("x");
ylabel("y");

n=size(X,1);% 点数
k=(n*sum(X.*Y)-sum(Y)*sum(X))/(n*sum(X.*X)-sum(X)*sum(X));
b=(sum(X.*X)*sum(Y)-sum(X)*sum(X.*Y))/(n*sum(X.*X)-sum(X)*sum(X));

hold on;
grid on;

f=@(x)k*x+b;
fplot(f,[2.5,7]);
legend("样本点","拟合结果函数","Location","southeast");

hold off;

y_hat=k.*X+b;
[R_2,SST,SSE,SSR]=getR(Y,y_hat);


% 预测美国人口
% year = 1790:10:2000;
% population = [3.9,5.3,7.2,9.6,12.9,17.1,23.2,31.4,38.6,50.2,62.9,76.0,92.0,106.5,123.2,131.7,150.7,179.3,204.0,226.5,251.4,281.4];


% 采用合适的拟合函数，预测中国人口

year = cnPopulation(:,1)'
population = cnPopulation(:,2)'
plot(year,population)
